<?php
/**
 * 默认展示页面
 *
 *
 *
 * @网店运维提供技术支持 授权请购买shopnc授权
 * @license    http://www.shopwwi.com
 * @link       交流群号：111731672
 */


defined('InShopNC') or exit('Access Invalid!');
require_once(BASE_ROOT_PATH."/shop/framework/function/crowd.php");
class crowdfundingControl extends BaseHomeControl{
    public function indexOp(){
//        showMessage('该活动已结束!','index.php');
        Language::read('home_index_index');
        Tpl::output('index_sign','crowdfunding');

        $model_crowd = Model("crowdlist");
        $winners = $model_crowd->getWinnerList(5); //最新揭晓
        Tpl::output('winners',$winners);

        $products = $model_crowd->getComingList(8);//即将揭晓
        Tpl::output('products',$products);

        $crowds = $model_crowd->getCrowdingList(12); //他们在云购
        Tpl::output('crowds_list',$crowds);

        $recommends = $model_crowd->getRenqiList(4,1);
        Tpl::output('recommends',$recommends);

        $ren_qirecommends = $model_crowd->getRenqiList(6,0);
        Tpl::output('ren_qirecommends',$ren_qirecommends);

        //板块信息
        $model_web_config = Model('web_config');
        $web_html = $model_web_config->getWebHtml('crowd');
        Tpl::output('web_html',$web_html);

        Model('seo')->type('crowdfunding')->show();

        Tpl::showpage('crowdfunding');
    }

    public function listOp(){
        $model_crowd = Model("crowdlist");
        $curpage = empty($_GET['curpage']) ? 1:(int)$_GET['curpage'];

        $condition = array('q_uid'=>array('exp','q_uid is null'));
        $order = "shenyurenshu ASC";
        $total_records = $model_crowd->table('crowdlist')->where($condition)->count();
        Tpl::output('total_records',$total_records);
        pagecmd('setTotalNum',$total_records);
        $limit = 20;
        pagecmd('setEachNum',$limit);
        Tpl::output('curpage',$curpage);
        Tpl::output('limit',$limit);
        $records = $model_crowd->getItems($condition, '*',  $order,$limit ,$curpage-1);
        Tpl::output('records',$records);
        Tpl::output('show_page', $model_crowd->showpage());
        Tpl::showpage('crowd_list');
    }

    public function recordsOp(){
        $model_crowd = Model("crowdlist");
        $curpage = empty($_GET['curpage']) ? 1:(int)$_GET['curpage'];

        $condition = array('q_uid'=>array('exp','q_uid is not null'));
        $condition['q_end_time'] = array('exp','q_end_time is not null');
        $order = "q_end_time DESC";
        $total_records = $model_crowd->table('crowdlist')->where($condition)->count();
        Tpl::output('total_records',$total_records);
        pagecmd('setTotalNum',$total_records);
        $limit = 20;
        pagecmd('setEachNum',$limit);
        Tpl::output('curpage',$curpage);
        Tpl::output('limit',$limit);
        $records = $model_crowd->getItems($condition, '*',  $order,$limit ,$curpage-1);
        Tpl::output('records',$records);
        Tpl::output('show_page', $model_crowd->showpage());

        $crowds = $model_crowd->getCrowdingList(12); //他们在云购
        Tpl::output('crowds_list',$crowds);

        $ren_qirecommends = $model_crowd->getRenqiList(6,0);
        Tpl::output('ren_qirecommends',$ren_qirecommends);


        Tpl::showpage('crowd_records');
    }

  public  function goodsOp(){
        $model_crowd = Model("crowdlist");
        $item = $model_crowd->getItem((int)$_GET['id']);
        if(!empty($item['q_uid'])){
          $items = $model_crowd->getItems(array('sid'=>$item['sid'],'q_uid'=>array('exp','q_uid is null')),'*','id DESC',1);
          redirect(urlShop('crowdfunding','goods',array('id'=>$items[0]['id'])));
        }
        $model_crowd->table('crowdlist')->where(array('id'=>(int)$_GET['id']))->setInc('renqipos',1);
        Tpl::output('item',$item);

        $sid = $item['sid'];
        $sid_item = $model_crowd->getLastItem(array('sid'=>$sid));
        Tpl::output('sid_item',$sid_item);

        $sid_go_record = $model_crowd->getLastGoRecord(array('shopid'=>$sid));
        Tpl::output('sid_go_record',$sid_go_record);

        $datas = get_record($model_crowd,$_SESSION['member_id'],$item['id'],9);
        Tpl::output('datas',$datas);

        $user_list = $model_crowd->getUserList(array('shopid'=>$item['id'],'shopqishu'=>$item['qishu']),6);
        Tpl::output('user_list',$user_list);

        $user_list_more = $model_crowd->getUserList(array('shopid'=>$item['id'],'shopqishu'=>$item['qishu']),50);
        Tpl::output('user_list_more',$user_list_more);
        $itemlist = $model_crowd->table("crowdlist")->where(array('sid'=>$item['sid'],'qishu'=>array('lt',$item['qishu'])))->field('id,sid,q_uid,qishu')->order('qishu DESC')->select();
        Tpl::output('itemlist',$itemlist);

        Tpl::showpage('goods');
    }

    public function dataserverOp(){
        $id = (int)$_GET['id'];
        $model_crowd = Model("crowdlist");
        $item = $model_crowd->getItem($id);
        if(empty($item))redirect(urlShop('crowdfunding','index'));
        if(empty($item['q_end_time'])){
            header("location: ".urlShop('crowdfunding','goods',array('id'=>$id)));
            exit;
        }
        if(empty($item['q_user_code'])){
            showMessage('该商品正在进行中...',urlShop('crowdfunding','goods',array('id'=>$id)));
        }
        //云购中奖码
        $q_user = unserialize($item['q_user']);
        $q_user_code_len = strlen($item['q_user_code']);
        $q_user_code_arr = array();
        for($q_i=0;$q_i < $q_user_code_len;$q_i++){
            $q_user_code_arr[$q_i] = substr($item['q_user_code'],$q_i,1);
        }
        //总云购次数
        $user_shop_number = $model_crowd->table('member_go_record')->where(array('member_id'=>$item['q_uid'],'shopid'=>$item['id'],'shopqishu'=>$item['qishu']))->count('gonumber');
        //用户云购时间
        $user_shop = $model_crowd->table('member_go_record')->where(array('member_id'=>$item['q_uid'],'shopid'=>$item['id'],'shopqishu'=>$item['qishu'],'huode'=>$item['q_user_code']))->find();
        $user_shop_time = $user_shop['time'];
        //得到云购码
        $user_shop_codes_arr = $model_crowd->table('member_go_record')->where(array('member_id'=>$item['q_uid'],'shopid'=>$item['id'],'shopqishu'=>$item['qishu']))->select();
        $user_shop_codes = '';
        foreach($user_shop_codes_arr as $v){
            $user_shop_codes .= $v['goucode'].',';
        }

        $user_shop_codes = rtrim($user_shop_codes,',');

        $h=abs(date("H",$item['q_end_time']));
        $i=date("i",$item['q_end_time']);
        $s=date("s",$item['q_end_time']);
        $w=substr($item['q_end_time'],11,3);
        $user_shop_time_add = $h.$i.$s.$w;
        $user_shop_fmod = fmod($user_shop_time_add*100,$item['canyurenshu']);

        if($item['q_content']){
            $item_q_content = unserialize($item['q_content']);
            $keysvalue = $new_array = array();
            foreach($item_q_content as $k=>$v){
                $keysvalue[$k] = $v['time'];
                $h=date("H",$v['time']);
                $i=date("i",$v['time']);
                $s=date("s",$v['time']);
                list($timesss,$msss) = explode(".",$v['time']);
                $item_q_content[$k]['timeadd'] = $h.$i.$s.$msss;

            }
            arsort($keysvalue);	//asort($keysvalue);正序
            reset($keysvalue);
            foreach ($keysvalue as $k=>$v){
                $new_array[$k] = $item_q_content[$k];
            }
            $item['q_content'] = $new_array;
        }



        $title=$item['title'].' ('.$item['title2'].')';
        $keywords = $item['keywords'];
        $description = $item['description'];

        $go_record_list =  $model_crowd->table('member_go_record')->where(array('shopid'=>$item['id'],'shopqishu'=>$item['qishu']))->order("id DESC")->limit(50)->select();
        $itemzx= $model_crowd->table("crowdlist")->where(array('sid'=>$item['sid'],'qishu'=>array('gt',$item['qishu'])))->order('qishu DESC')->find();

        //期数显示
        $itemlist = $model_crowd->table("crowdlist")->where(array('sid'=>$item['sid']))->field('id,sid,q_uid,qishu')->order('qishu DESC')->select();
        $loopqishu='<ul class="Period_list">';
        if(empty($itemlist[0]['q_uid'])){
            $loopqishu.='<li><a href="'.urlShop('crowdfunding','goods',array('id'=>$itemlist[0]['id'])).'"><b class="period_Ongoing">'."第".$itemlist[0]['qishu']."期<i></i></b></a></li>";
            unset($itemlist[0]);
        }else{
            $loopqishu.='<li><a href="'.urlShop('crowdfunding','goods',array('id'=>$itemlist[0]['id'])).'"><b class="period_ArrowCur">'."第".$itemlist[0]['qishu']."期<i></i></b></a></li>";
            unset($itemlist[0]);
        }
        if(empty($itemlist)){
            $loopqishu.='</ul>';
        }

        foreach($itemlist as $key=>$qitem){
            if($key%9==0){
                $loopqishu.='</ul><ul class="Period_list">';
            }
            if($qitem['id'] == $item['id']){
                $loopqishu.='<li><b class="period_ArrowCur">第'.$qitem['qishu'].'期</b></li>';
            }else{
                $loopqishu.='<li><a href="'.urlShop('crowdfunding','dataserver',array('id'=>$itemlist[0]['id'])).'" class="gray02">第'.$qitem['qishu'].'期</a></li>';
            }
        }
        Tpl::output('q_user',$q_user);
        Tpl::output('user_shop_time',$user_shop_time);
        Tpl::output('user_shop_number',$user_shop_number);
        Tpl::output('q_user_code_arr',$q_user_code_arr);
        Tpl::output('user_shop_codes',$user_shop_codes);
        Tpl::output('user_shop_time_add',$user_shop_time_add);
        Tpl::output('user_shop_fmod',$user_shop_fmod);
        Tpl::output('item',$item);
        Tpl::output('itemzx',$itemzx);
        Tpl::output('loopqishu',$loopqishu);
        Tpl::showpage('dataserver');
    }

  public  function go_record_iframOp(){
        $model_crowd = Model("crowdlist");
        $condition = array('shopid'=>(int)$_GET['id']);
        $go_record_list = $model_crowd->getGoRecordList($condition, 20, '*', 'id desc','', '');
        Tpl::output('pagenum',20);
        Tpl::output('go_record_list',$go_record_list);
        Tpl::output('show_page',$model_crowd->showpage());
        Tpl::showpage('go_record_iframe','null_layout');
    }

  public function go_itmeiframOp(){
      $model_crowd = Model("crowdlist");
      $item = $model_crowd->getItem((int)$_GET['id']);
      Tpl::output('item',$item);
      $items = $model_crowd->getItems(array('sid'=>$item['sid']),'id');
      $ids = array();
      foreach($items as $i){
         $ids[] = $i['id'];
      }
      $model_shaidan = Model("shaidan");
      $condition = array('sd_shop'=>array('in',$ids));
      $shaidan_list = $model_shaidan->getShaidanList($condition,20,'*','sd_id DESC');
      Tpl::output('shaidan_list',$shaidan_list);

      Tpl::showpage('go_itmeiframe','null_layout');

  }

  public function cartlistOp(){
      $this->Cartlist = $_COOKIE['Cartlist'];
      $Cartlist=json_decode(stripslashes($this->Cartlist),true);
      $shopids=array();
      if(is_array($Cartlist)){
          foreach($Cartlist as $key => $val){
              if($key!=0)
              $shopids[]=intval($key);
          }
      }

      $model_crowd = Model("crowdlist");
      $shoplist = $model_crowd->getItems(array('id'=>array('in',$shopids)));
      $MoenyCount=0;
      $Cartshopinfo='{';
      if(count($shoplist)>=1){
          foreach($Cartlist as $key => $val){
              $key=intval($key);
              for($i=0;$i<count($shoplist);$i++) {
                  if ($shoplist[$i]['id']==$key) {
                      $shoplist[$i]['cart_gorenci'] = $val['num'] ? $val['num'] : 1;
                      $MoenyCount += $shoplist[$i]['yunjiage'] * $shoplist[$i]['cart_gorenci'];
                      $shoplist[$i]['cart_xiaoji'] = substr(sprintf("%.3f", $shoplist[$i]['yunjiage'] * $val['num']), 0, -1);
                      $shoplist[$i]['cart_shenyu'] = $shoplist[$i]['zongrenshu'] - $shoplist[$i]['canyurenshu'];
                      $Cartshopinfo .= "'$key':{'shenyu':" . $shoplist[$i]['cart_shenyu'] . ",'num':" . $val['num'] . ",'money':" . $shoplist[$i]['yunjiage'] . "},";
                  }
              }
          }
      }

      $getlist = $model_crowd->getItems(array('q_uid'=>array('exp','q_uid is null')),'*','rand()');
      Tpl::output('getlist',$getlist);

      $MoenyCount=substr(sprintf("%.3f",$MoenyCount),0,-1);
      $Cartshopinfo.="'MoenyCount':$MoenyCount}";
      Tpl::output('MoenyCount',$MoenyCount);
      Tpl::output('Cartshopinfo',$Cartshopinfo);
      Tpl::output('shoplist',$shoplist);
      Tpl::showpage('cart.cartlist');
  }

  public function cart_payOp(){
      $member_info = $this->getMemberAndGradeInfo(true);
      if(!$member_info){
          showMessage('请先登入会员后再操作!','/member/index.php?act=login&op=index');
      }
      $this->Cartlist = $_COOKIE['Cartlist'];
      $Cartlist=json_decode(stripslashes($this->Cartlist),true);
      $shopids=array();
      if(is_array($Cartlist)){
          foreach($Cartlist as $key => $val){
              if($key!=0)
                  $shopids[]=intval($key);
          }
      }
      $model_crowd = Model("crowdlist");
      $shoplist = $model_crowd->getItems(array('id'=>array('in',$shopids)));
      $MoenyCount=0;
      $Cartshopinfo='{';
      if(count($shoplist)>=1){
          foreach($Cartlist as $key => $val){
              $key=intval($key);
              for($i=0;$i<count($shoplist);$i++) {
                  if ($shoplist[$i]['id']==$key) {
                      $shoplist[$i]['cart_gorenci'] = $val['num'] ? $val['num'] : 1;
                      $MoenyCount += $shoplist[$i]['yunjiage'] * $shoplist[$i]['cart_gorenci'];
                      $shoplist[$i]['cart_xiaoji'] = substr(sprintf("%.3f", $shoplist[$i]['yunjiage'] * $val['num']), 0, -1);
                      $shoplist[$i]['cart_shenyu'] = $shoplist[$i]['zongrenshu'] - $shoplist[$i]['canyurenshu'];
                      $Cartshopinfo .= "'$key':{'shenyu':" . $shoplist[$i]['cart_shenyu'] . ",'num':" . $val['num'] . ",'money':" . $shoplist[$i]['yunjiage'] . "},";
                      $CartTitle[$shoplist[$i]['id']]= $shoplist[$i]['title'];
                  }
              }
          }
      }
      $go_records = $model_crowd->getGoRecordList(array('member_id'=>$member_info['member_id'],'shopid'=>array('in',$shopids), 'huode'=>0,'status'=>'已付款,未发货,未完成'));
      if(!empty($go_records)){
          $title_alert = '';
          foreach($go_records as $record){
              $title_alert .= $CartTitle[$record['shopid']]." ";
          }
      }
      if(!empty($title_alert)){
          showMessage('一个产品只允许一个会员参与一次'."\n ".$title_alert.'已经参与了,请删除或等待目前活动结束后再参与.','index.php?act=crowdfunding&op=cartlist');
      }else {
          $getlist = $model_crowd->getItems(array('q_uid' => array('exp', 'q_uid is null')), '*', 'shenyurenshu ASC');
          Tpl::output('getlist', $getlist);

          $MoenyCount = substr(sprintf("%.3f", $MoenyCount), 0, -1);
          $Cartshopinfo .= "'MoenyCount':$MoenyCount}";
          Tpl::output('MoenyCount', $MoenyCount);
          Tpl::output('Cartshopinfo', $Cartshopinfo);
          Tpl::output('shoplist', $shoplist);

          //会员余额
          $Money = (float)$member_info['available_predeposit'];


          //显示支付接口列表
          $model_payment = Model('payment');
          $condition = array();
          $payment_list = $model_payment->getPaymentOpenList($condition);
          if (!empty($payment_list)) {
              unset($payment_list['predeposit']);
              unset($payment_list['offline']);
          }
          if (empty($payment_list)) {
              showMessage('暂未找到合适的支付方式', 'index.php?act=member_order', 'html', 'error');
          }
          Tpl::output('payment_list', $payment_list);

          //显示预存款、支付密码、充值卡
          $available_predeposit = $available_rc_balance = 0;
          $buyer_info = Model('member')->getMemberInfoByID($_SESSION['member_id']);
          if (floatval($buyer_info['available_predeposit']) > 0) {
              $available_predeposit = (float)$buyer_info['available_predeposit'];
          }
          if (floatval($buyer_info['available_rc_balance']) > 0) {
              $available_rc_balance = (float)$buyer_info['available_rc_balance'];
          }
          $member_paypwd = $buyer_info['member_paypwd'] ? true : false;

          Tpl::output('available_predeposit', $available_predeposit);
          Tpl::output('available_rc_balance', $available_rc_balance);
          Tpl::output('member_paypwd', $member_paypwd);

          session_start();
          $_SESSION['submitcode'] = $submitcode = uniqid();
          Tpl::output('submitcode', $submitcode);
          //商品数量
          $shoplen = count($shoplist);
          Tpl::output('shoplen', $shoplen);
          Tpl::output('Money', $Money);
          Tpl::showpage('cart.pay');
      }
  }

    /**
     * 下单时支付页面
     */
    public function paysubmitOp() {
        session_start();
        if($_POST['submitcode']!=$_SESSION['submitcode']){ //表单验证
            showMessage('表单提交错误!','index.php?act=crowdfunding&op=cart_pay');
        }
        if (!$_SESSION['member_id'] ){
            redirect(urlLogin('login', 'index', array('ref_url' => 'index.php?act=crowdfunding&op=cart_pay')));
        }

        $buyer_info = Model('member')->getMemberInfoByID($_SESSION['member_id']);
        $obj = array();
        $obj['Cartlist'] = $_COOKIE['Cartlist'];
        $Cartlist=json_decode(stripslashes($obj['Cartlist']),true);
        $shopids=array();
        if(is_array($Cartlist)){
            foreach($Cartlist as $key => $val){
                if($key!=0)
                    $shopids[]=intval($key);
            }
        }

        $model_crowd = Model("crowdlist");
        $shoplist = $model_crowd->getItems(array('id'=>array('in',$shopids)));
        $MoenyCount=0;
        $Cartshopinfo='{';
        if(count($shoplist)>=1){
            foreach($Cartlist as $key => $val){
                $key=intval($key);
                for($i=0;$i<count($shoplist);$i++) {
                    if ($shoplist[$i]['id']==$key) {
                        $shoplist[$i]['cart_gorenci'] = $val['num'] ? $val['num'] : 1;
                        $MoenyCount += $shoplist[$i]['yunjiage'] * $shoplist[$i]['cart_gorenci'];
                        $shoplist[$i]['cart_xiaoji'] = substr(sprintf("%.3f", $shoplist[$i]['yunjiage'] * $val['num']), 0, -1);
                        $shoplist[$i]['cart_shenyu'] = $shoplist[$i]['zongrenshu'] - $shoplist[$i]['canyurenshu'];
                        $Cartshopinfo .= "'$key':{'shenyu':" . $shoplist[$i]['cart_shenyu'] . ",'num':" . $val['num'] . ",'money':" . $shoplist[$i]['yunjiage'] . "},";
                        $CartTitle[$shoplist[$i]['id']]= $shoplist[$i]['title'];
                    }
                }
            }
        }

        $obj['members'] = $buyer_info;
        $obj['MoneyCount'] = $MoenyCount;
        $obj['members']['money'] = $buyer_info['available_rc_balance']+$buyer_info['available_predeposit'];

        if($_POST['pd_pay']||$_POST['rcb_pay']) {
            if (md5($_POST['password']) != $buyer_info['member_paypwd']) {
                showMessage('支付密码不正确!', 'index.php?act=crowdfunding&op=cart_pay');
            }
            if ($_POST['rcb_pay']) {
                if ($buyer_info['available_rc_balance'] < $MoenyCount) {
                    showMessage('充值卡余额不足,请重新选择!', 'index.php?act=crowdfunding&op=cart_pay');
                }
            }
            if ($_POST['pd_pay']) {
                if ($buyer_info['available_predeposit'] < $MoenyCount) {
                    showMessage('预存款余额不足,请重新选择!', 'index.php?act=crowdfunding&op=cart_pay');
                }
            }

            $go_records = $model_crowd->getGoRecordList(array('member_id' => $buyer_info['member_id'], 'shopid' => array('in', $shopids), 'huode' => 0, 'status' => '已付款,未发货,未完成'));
            if (!empty($go_records)) {
                $title_alert = '';
                foreach ($go_records as $record) {
                    $title_alert .= $CartTitle[$record['shopid']] . " ";
                }
            }
            if (!empty($title_alert)) {
                showMessage('一个产品只允许一个会员参与一次' . "\n " . $title_alert . '已经参与了,请删除或等待目前活动结束后再参与.', 'index.php?act=crowdfunding&op=cartlist');
            } else {

                //扣款,写入订单
                if ($obj['members']['money'] >= $MoenyCount) {
                    $obj = go_record($model_crowd, $obj);
                    if ($obj['ok'] !== 'ok') {
                        $_COOKIE['Cartlist'] = NULL;
                        setcookie("Cartlist", '', -3600,'/');
                        showMessage($obj['ok']);
                    }
                    $check = go_pay($model_crowd, $obj, true);
                } else {
                    showMessage('余额不足,请先充值后再继续!', 'index.php?act=crowdfunding&op=cart_pay');
                }

            if ($check) {
                $_COOKIE['Cartlist'] = NULL;
                setcookie("Cartlist", '', -3600,'/');
                $getlist = $model_crowd->getItems(array('q_uid' => array('exp', 'q_uid is null')), '*', 'shenyurenshu ASC');
                Tpl::output('getlist', $getlist);
                Tpl::showpage('cart.paysuccess');
            } else {
                showMessage('支付失败,请稍后再试!', 'index.php?act=crowdfunding&op=cart_pay');
            }
          }
        }
    }

    public function fengxiangOp(){
        $model_member = Model("member");
        $list = $model_member->table("member_invite,member")->join('left')->on("(member.member_name=member_invite.user_id)")->field('count(member_invite.invite_mobile) as num,member.member_nickname,user_id,member_name')->group('user_id')->order('num DESC')->limit('0,6')->select();
        Tpl::output('list',$list);
        Tpl::showpage('fengxiang');
    }

}
